package com.qifenqian.turbot.module.ui.setting

import android.content.Context
import android.content.Intent
import android.view.View
import com.blankj.rxbus.RxBus
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.module.contract.AccountContract
import com.qifenqian.turbot.module.presenter.AccountPresenter
import com.qifenqian.turbot.module.ui.loginetc.ForgetPasswordActivity
import com.qifenqian.turbot.module.ui.loginetc.START_FROM_MODIFY_PASSWORD
import com.qifenqian.turbot.util.Lcat
import kotlinx.android.synthetic.main.activity_modify_password.*
import org.jetbrains.anko.toast

class ModifyPasswordActivity : BaseActivity<AccountPresenter, AccountContract.View>(), AccountContract.View {

    companion object {
        fun startThis(context: Context) {
            val intent = Intent(context, ModifyPasswordActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_modify_password
    }

    override fun bindPresenter(): AccountPresenter? {
        return AccountPresenter(this, this)
    }

    override fun initial() {
        //如果点击忘记密码,跳转到忘记密码界面的时候,修改密码成功之后,通知关闭该页面
        //TODO:需要验证效果
        //备选方案, 使用ActivityCollector,或者直接finish
        RxBus.getDefault().subscribe(this, START_FROM_MODIFY_PASSWORD, object : RxBus.Callback<Boolean>() {
            override fun onEvent(t: Boolean?) {
                if (t != null && t) {
                    finish()
                    Lcat.a("忘记密码成功会关闭修改密码界面吗?", t)
                }
            }
        })
        btn_modify_password_forget.setOnClickListener {
            ForgetPasswordActivity.startThis(this)

        }
        btn_modify_password_next.setOnClickListener {
            if (et_modify_password_old.text.toString().isBlank()) {
                toast("请输入原密码")
                return@setOnClickListener
            }
            if (et_modify_password_new.text.toString().isBlank()) {
                toast("请输入新密码")
                return@setOnClickListener
            }
            if (et_modify_password_confirm.text.toString().isBlank()) {
                toast("请确认密码")
                return@setOnClickListener
            }
            mPresenter!!.modifyPassword(et_modify_password_old.text.toString(), et_modify_password_confirm.text.toString())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.getDefault().unregister(this)
    }

    override fun modifyPasswordResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finish()
        } else {
            when (code) {
                5 -> btn_modify_password_forget.visibility = View.VISIBLE   //原密码错误
            }
        }
        toast(msg!!)
    }

}
